package 单词搜索;

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * @param board string字符串一维数组
     * @param word string字符串
     * @return bool布尔型
     */
    static int N = 110, n, m;
    static boolean[][] st = new boolean[N][N];
    static int[] dx = {-1, 1, 0, 0};
    static int[] dy = {0, 0, -1, 1};

    public boolean exist(String[] board, String word) {
        n = board.length;
        m = board[0].length();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (board[i].charAt(j) == word.charAt(0)) {
                    for (int k = 0; k < n; k++) {
                        Arrays.fill(st[k], false);
                    }
                    PII start = new PII(i, j);
                    if (dfs(start, board, word, 1)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private boolean dfs(PII start, String[] board, String word, int u) {
        if (u == word.length()) {
            return true;
        }
        st[start.x][start.y] = true;
        for (int i = 0; i < 4; i++) {
            int a = start.x + dx[i];
            int b = start.y + dy[i];
            if (a < 0 || a >= n || b < 0 || b >= m) {
                continue;
            }
            if (st[a][b]) {
                continue;
            }
            if (board[a].charAt(b) != word.charAt(u)) {
                continue;
            }
            if (dfs(new PII(a, b), board, word, u + 1)) {
                return true;
            }
        }
        st[start.x][start.y] = false;
        return false;
    }
}

class PII {
    int x, y;

    public PII(int x, int y) {
        this.x = x;
        this.y = y;
    }
}